package common.util;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.util.ResourceUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;

/**
 * @作者：caopengfei
 * @时间：2020/3/26
 */
@Slf4j
public class FileUtil {

    public static void exportExcel_XZ(File tempFile, HttpServletResponse response) {
        FileInputStream fs = null;
        OutputStream os =null;
        try {
            fs = new FileInputStream(tempFile);
            response.setContentType("APPLICATION/DOWNLOAD");
            response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder
                    .encode(tempFile.getName(),"UTF-8"));
            response.setContentLength(fs.available());
            os = response.getOutputStream();
            int iBytesRead = 0;
            byte[] buffer = new byte[8192];
            while((iBytesRead = fs.read(buffer,0,8192))!=-1){
                os.write(buffer,0,iBytesRead);
            }
            response.flushBuffer();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                fs.close();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public  static void exportExcel(HttpServletResponse response, String templePath, String fileName, String sheetName,Map map) {
        String path = "";
        try {
            File mbFile = ResourceUtils.getFile(templePath);
            path = mbFile.getAbsolutePath();
        } catch (FileNotFoundException e) {

        }
        TemplateExportParams params = new TemplateExportParams(
                path,true);
        params.setSheetName(new String [] {sheetName});
        Workbook workbook = ExcelExportUtil.exportExcel(params, map);
        File savefile = new File("D:/doc/excel/");
        if (!savefile.exists()) {
            savefile.mkdirs();
        }
        String pathName = "D:/doc/excel/" + fileName;
        try {
            File file = new File(pathName);
            FileOutputStream fos = new FileOutputStream(pathName);
            workbook.write(fos);
            exportExcel_XZ(file,response);
        } catch (Exception e) {
            log.error("导出失败",e);
        }
    }
}
